package com.web3.management.controller;

import com.web3.management.dto.ApiResponse;
import com.web3.management.dto.PageResponse;
import com.web3.management.dto.request.TradeLogBatchRequest;
import com.web3.management.dto.request.TradeLogRequest;
import com.web3.management.dto.response.AccountDetailResponse;
import com.web3.management.dto.response.EffectiveConfigResponse;
import com.web3.management.dto.response.TradeDailyStatsResponse;
import com.web3.management.dto.response.TradeLogResponse;
import com.web3.management.security.AccountClientPrincipal;
import com.web3.management.security.SecurityUtils;
import com.web3.management.service.AccountService;
import com.web3.management.service.AccountConfigService;
import com.web3.management.service.TradeLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户端API控制器
 * 通过token直接获取当前账号信息，无需传递accountId参数
 */
@RestController
@RequestMapping("/api/client")
@RequiredArgsConstructor
@PreAuthorize("hasRole('ROLE_ACCOUNT_CLIENT')")
@Validated
public class ClientController {

    private final AccountService accountService;
    private final AccountConfigService accountConfigService;
    private final TradeLogService tradeLogService;

    /**
     * 获取当前账号信息
     */
    @GetMapping("/account")
    public ApiResponse<AccountDetailResponse> getCurrentAccount() {
        AccountClientPrincipal principal = SecurityUtils.getAccountClientPrincipal();
        Integer accountId = principal.getAccountId();
        return ApiResponse.success(accountService.getAccountDetail(accountId));
    }

    /**
     * 获取当前账号的有效配置
     */
    @GetMapping("/effective-config")
    public ApiResponse<EffectiveConfigResponse> getCurrentEffectiveConfig() {
        AccountClientPrincipal principal = SecurityUtils.getAccountClientPrincipal();
        Integer accountId = principal.getAccountId();
        EffectiveConfigResponse response = accountConfigService.getEffectiveConfig(accountId);
        return ApiResponse.success(response);
    }

    /**
     * 记录当前账号的交易日志
     */
    @PostMapping("/trade-logs")
    public ApiResponse<TradeLogResponse> saveTradeLog(@Valid @RequestBody TradeLogRequest request) {
        AccountClientPrincipal principal = SecurityUtils.getAccountClientPrincipal();
        Integer accountId = principal.getAccountId();

        // 强制设置accountId为当前token对应的账号
        request.setAccountId(accountId);

        TradeLogResponse response = tradeLogService.saveLog(request);
        return ApiResponse.success("日志记录成功", response);
    }

    /**
     * 批量记录当前账号的交易日志
     */
    @PostMapping("/trade-logs/batch")
    public ApiResponse<List<TradeLogResponse>> saveTradeLogs(@Valid @RequestBody TradeLogBatchRequest request) {
        AccountClientPrincipal principal = SecurityUtils.getAccountClientPrincipal();
        Integer accountId = principal.getAccountId();

        // 强制设置所有日志的accountId为当前token对应的账号
        if (request.getLogs() != null) {
            request.getLogs().forEach(log -> log.setAccountId(accountId));
        }

        List<TradeLogResponse> responses = tradeLogService.saveLogs(request.getLogs());
        return ApiResponse.success("批量日志记录成功", responses);
    }

    /**
     * 查询当前账号的交易日志
     */
    @GetMapping("/trade-logs")
    public ApiResponse<PageResponse<TradeLogResponse>> getTradeLogs(
            @RequestParam(required = false) Integer accountConfigId,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @RequestParam(defaultValue = "1") @Min(1) Integer page,
            @RequestParam(defaultValue = "20") @Min(1) @Max(200) Integer size) {
        AccountClientPrincipal principal = SecurityUtils.getAccountClientPrincipal();
        Integer accountId = principal.getAccountId();

        PageResponse<TradeLogResponse> response = tradeLogService.queryLogs(accountId, accountConfigId, startDate, endDate, page, size);
        return ApiResponse.success(response);
    }

    /**
     * 获取当前账号的每日交易统计
     */
    @GetMapping("/stats/trade/daily")
    public ApiResponse<List<TradeDailyStatsResponse>> getDailyStats(
            @RequestParam(required = false) Integer accountConfigId,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        AccountClientPrincipal principal = SecurityUtils.getAccountClientPrincipal();
        Integer accountId = principal.getAccountId();

        List<TradeDailyStatsResponse> stats = tradeLogService.getDailyStats(accountId, accountConfigId, startDate, endDate);
        return ApiResponse.success(stats);
    }

    /**
     * 检查是否需要重启客户端
     * 基于账号表的needsRestart字段
     */
    @GetMapping("/restart-check")
    public ApiResponse<Map<String, Object>> checkRestart() {
        AccountClientPrincipal principal = SecurityUtils.getAccountClientPrincipal();
        Integer accountId = principal.getAccountId();

        // 获取当前账号信息
        AccountDetailResponse account = accountService.getAccountDetail(accountId);

        Map<String, Object> result = new HashMap<>();
        result.put("shouldRestart", account.getNeedsRestart() != null && account.getNeedsRestart());
        result.put("needsRestart", account.getNeedsRestart());
        result.put("lastRestartTime", account.getLastRestartTime());
        result.put("checkTime", System.currentTimeMillis());

        return ApiResponse.success(result);
    }

    /**
     * 确认重启完成，清除重启标志并更新重启时间
     */
    @PostMapping("/restart-confirm")
    public ApiResponse<Void> confirmRestart() {
        AccountClientPrincipal principal = SecurityUtils.getAccountClientPrincipal();
        Integer accountId = principal.getAccountId();

        // 清除重启标志并更新重启时间
        accountService.confirmRestart(accountId);

        return ApiResponse.success("重启确认成功", null);
    }

    /**
     * 上报客户端错误信息
     */
    @PostMapping("/report-error")
    public ApiResponse<Void> reportError(@RequestBody Map<String, Object> request) {
        AccountClientPrincipal principal = SecurityUtils.getAccountClientPrincipal();
        Integer accountId = principal.getAccountId();

        String errorMessage = (String) request.get("errorMessage");
        String errorType = (String) request.getOrDefault("errorType", "UNKNOWN");

        // 上报错误信息
        accountService.reportError(accountId, errorMessage, errorType);

        return ApiResponse.success("错误信息上报成功", null);
    }
}